﻿using BLToolkit.Data.Linq;
using CommonLibrary;
using CommonLibrary.Interface;
using CommonLibrary.Models;
using CommonLibrary.WorkFlow;
using CommonSite.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CommonSite.Controllers
{
    [UserAuthorizeAttribute]
    public class WorkController : Controller
    {
        public ActionResult Index()
        {
            using (CommonDatabase db = new CommonDatabase())
            {
                var user = UserAction.GetCurrentUser().UserId;

                var cmd = @"select * from view_workitem where state = 1 and workuserid = @user order by id;";
                var dt = db.SetCommand(cmd, db.Parameter("@user", user))
                           .ExecuteDataTable();

                ViewBag.Total = dt.Rows.Count;
                ViewBag.Rows = JSON.ToString(dt);
            }

            return View();
        }

        [HttpGet]
        public ActionResult Info(int taskobjectid)
        {
            try
            {
                using (var db = new CommonDatabase())
                {
                    var workitem = db.SetCommand(
                                        "select * from wf_taskobject where id = @id and state = 1",
                                        db.Parameter("@id", taskobjectid))
                                     .ExecuteDataTable().Rows[0];
                    var flow = db.SetCommand(
                                    "select * from view_flowobject where id = @id",
                                    db.Parameter("@id", (int)workitem["flowobjectid"]))
                                 .ExecuteDataTable().Rows[0];
                    var form = db.wf_FormInstance.Where(k => k.Id == (int)flow["forminstanceid"]).First();
                    var fields = db.wf_FieldInstance.Where(k => k.FormId == (int)flow["forminstanceid"]).ToList();
                    var row = db.SetCommand(
                                    string.Format(
                                        "select * from workflow.form_{0} where Id = @id",
                                        form.Id),
                                    db.Parameter("@id", (int)flow["dataid"]))
                                .ExecuteDataTable().Rows[0];

                    ViewBag.Flow = flow;
                    ViewBag.WorkItem = workitem;
                    ViewBag.Form = form;
                    ViewBag.Fields = fields;
                    ViewBag.Row = row;
                }

                return View();
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        [HttpPost]
        public ActionResult Info(int taskobjectid, int state, string result)
        {
            using (CommonDatabase db = new CommonDatabase(CommonOption.ReadWrite))
            {
                db.BeginTransaction();

                WorkFlowManager manager = new WorkFlowManager(db);
                manager.Execute(taskobjectid, new Dictionary<string, object>() 
                {
                    { "state", state },
                    { "result", result }
                });

                db.CommitTransaction();
            }

            return RedirectToAction("Index");
        }

        public ActionResult Histories()
        {
            return View();
        }

        /// <summary>
        /// 获取审批历史记录
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult GetHistories(int? page, int? pagesize)
        {
            using (CommonDatabase db = new CommonDatabase())
            {
                if (page == null || page <= 0) page = 1;
                if (pagesize == null || pagesize <= 0) pagesize = 10;

                var cmd = @"select * from view_workitem where workuserid = @user order by id desc offset @p1 limit @p2";
                var dt = db.SetCommand(
                    cmd,
                    db.Parameter("@user", UserAction.GetCurrentUser().UserId),
                    db.Parameter("@p1", (page.Value - 1) * pagesize.Value),
                    db.Parameter("@p2", pagesize.Value))
                           .ExecuteDataTable();

                var count = db.SetCommand(
                                    "select count(*) from wf_taskobject where workuserid = @user",
                                    db.Parameter("@user", UserAction.GetCurrentUser().UserId))
                              .ExecuteScalar<int>();
                return Content(JSON.ToString(new 
                { 
                    Total = count,
                    Rows = dt 
                }));
            }
        }

        /// <summary>
        /// 指派他人审批
        /// </summary>
        /// <param name="flowid"></param>
        /// <param name="nodeid"></param>
        /// <param name="userid"></param>
        /// <param name="positionid"></param>
        /// <param name="orgid"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public ActionResult ChangeWorkUser(
            int taskObjectId,
            string userid,
            string result)
        {
            try
            {
                int _userId = CryptHelper.DecryptToInt32(userid);
                using (var db = new CommonDatabase())
                {
                    db.BeginTransaction();

                    WorkFlowManager manager = new WorkFlowManager(db);
                    manager.Execute(taskObjectId, new Dictionary<string, object>() 
                    {
                        { "state", 3 },
                        { "result", result },
                        { "userId", _userId }
                    });

                    db.CommitTransaction();
                }
            }
            catch
            {
            }

            return RedirectToAction("Index");
        }
    }
}
